<?php

namespace ApiBundle\Controller\User;


use ApiBundle\Controller\BaseController;
use Symfony\Component\HttpFoundation\Request;

class ArticleController extends BaseController
{
    /*
     *
     * 消息列表 is_training 0 所有, 1 通知消息, 2 培训消息
     */
    public function articleListAction(Request $request)
    {
        $conn = $this->get("database_connection");
        $token = $request->get("token");
        // TODO: 判断登录
        if(!$this->isLogged($conn)){
            return $this->response;
        }

        $is_training =$request->get("is_training");

        $is_read = $request->get("is_read");
        // 所有消息

        $sql = " SELECT a.* FROM article a LEFT JOIN training t ON a.training_id = t.id WHERE 1";

        // TODO 搜索
        $search = $request->get("search_keyword");

        if(!empty($search)){
            $sql .= " AND ( a.title LIKE '%". $search ."%' OR t.training_title_keyword LIKE '%". $search ."%' OR t.training_agency_keyword LIKE '%". $search ."%' )";
        }


        if($is_training == '0' || $is_training == NULL)
        {
            $sql .= " AND a.id IN (SELECT article_id FROM user_article WHERE user_id = '". $this->getUserId() ."') ";
        }

        // 公告
        if($is_training == '1')
        {
            // 未读
            if($is_read == "0"){
                $sql .= " AND a.id IN (SELECT article_id FROM user_article WHERE user_id = '". $this->getUserId() ."' AND is_read = 0 ) AND a.training_id IS NULL ";
            } else if($is_read == "1"){
                $sql .= " AND a.id IN (SELECT article_id FROM user_article WHERE user_id = '". $this->getUserId() ."' AND is_read = 1 ) AND a.training_id IS NULL ";
            } else {
                $sql .= " AND a.training_id IS NULL AND a.id IN (SELECT article_id FROM user_article WHERE user_id = '". $this->getUserId() ."') ";
            }
        }

        // 培训消息
        if($is_training == '2')
        {
            if($is_read == "0"){
                $sql .= " AND a.id IN (SELECT article_id FROM user_article WHERE user_id = '". $this->getUserId() ."' AND is_read = 0 ) AND training_id IS NOT NULL ";
            } else if($is_read == "1"){
                $sql .= " AND a.id IN (SELECT article_id FROM user_article WHERE user_id = '". $this->getUserId() ."' AND is_read = 1 ) AND training_id IS NOT NULL ";
            } else {
                $sql .= " AND a.training_id IS NOT NULL AND a.id IN (SELECT article_id FROM user_article WHERE user_id = '". $this->getUserId() ."') ";
            }
        }


        $sql .= " ORDER BY created_at DESC ";

//        var_dump($sql);exit;
        $article = $conn->fetchAll($sql);

        // 通知公告,培训消息-未读消息数
        $public_not_read_num = $conn->fetchColumn("SELECT count(*) FROM article WHERE id IN (SELECT article_id FROM user_article WHERE user_id = '". $this->getUserId() ."' AND is_read = 0 ) AND training_id IS NULL ORDER BY created_at DESC");
        $training_no_read_num = $conn->fetchColumn("SELECT count(*) FROM article WHERE id IN (SELECT article_id FROM user_article WHERE user_id = '". $this->getUserId() ."' AND is_read = 0 ) AND training_id IS NOT NULL ORDER BY created_at DESC");
        $all_count = array(
            "training_no_read_num" => $training_no_read_num,
            "public_not_read_num" => $public_not_read_num,
            "curr_date" => date('Y-m-d')
        );

        $data = array_merge(array("info" => $article),$all_count);

        return $this->jsonResponse(0,"操作成功",$data);
    }

    /*
     * 消息详情
     */
    public function articleInfoAction(Request $request)
    {
        $conn = $this->get("database_connection");

        // TODO: 判断登录
        if(!$this->isLogged($conn)){
            return $this->response;
        }

        $id = $request->get("id");

        if(empty($id)){
            return $this->jsonResponse(1,"参数错误");
        }

        $data = $conn->fetchAssoc("SELECT ad.nickname as admin_nickname, ad.realname as admin_name,ar.admin_id,ar.training_id,ar.title,ar.content,ar.summary,ar.created_at,ar.attachment_id,ar.updated_at,att.path,att.origin_name,att.size FROM article ar LEFT JOIN attachment att ON ar.attachment_id = att.id LEFT JOIN admin ad ON ad.id = ar.admin_id WHERE ar.id = '". $id ."' ");


        $training_id = $data['training_id'];


        if($training_id != NULL){
            $info = $conn->fetchAssoc("SELECT training_no, training_start_at, training_end_at, training_agency, trainer, participant, training_title_keyword, training_agency_keyword FROM training WHERE id = '". $training_id ."'");

            $data = array_merge($data, $info);
        }

        // TODO: 设置已读
        $where = array(
            "user_id" => $this->getUserId(),
            "article_id" => $id
        );

        $conn->update("user_article",array("is_read" => "1"),$where);

        return $this->jsonResponse(0,"操作成功",$data);

    }


    /*
     * 获取用户信息（用于报名）
     */
    public function getUserMessageAction()
    {
        $conn = $this->get("database_connection");

        if(!$this->isLogged($conn)){
            return $this->response;
        }

        $sql = "SELECT u.*, d.name as district FROM user u LEFT JOIN district d ON u.district_id = d.id ";

        $sql .= " WHERE u.id = '". $this->getUserId() ."'";
        $user = $conn->fetchAssoc($sql);

        $admin_sql = " SELECT nickname FROM admin WHERE id IN (SELECT admin_id FROM company WHERE id = '". $user['company_id'] ."')";

        $admin = $conn->fetchAssoc($admin_sql);
        $user['admin_nickname'] = $admin['nickname'];

        return $this->jsonResponse(0,"操作成功",$user);
    }

    /*
     * 报名判断
     */
    public function isApplyAction(Request $request)
    {
        $conn = $this->get("database_connection");
        if(!$this->isLogged($conn)){
            return $this->response;
        }

        $training_id = $request->get("training_id");

        if(empty($training_id)){

            return $this->jsonResponse(1,"参数错误");
        }

        $apply = $conn->fetchAssoc("SELECT * FROM apply WHERE user_id = '". $this->getUserId() ."' AND training_id = '". $training_id ."'");
        if($apply){
            return $this->jsonResponse(10,"已报名");
        }
        return $this->jsonResponse(0,"未报名");
    }


    /*
     * 报名
     */
    public function applyAction(Request $request)
    {
        $conn = $this->get("database_connection");
        if(!$this->isLogged($conn)){
            return $this->response;
        }
        $training_id = $request->get("training_id");
        $user_name = $request->get("name");
        $phone = $request->get("phone");
        //$company_name = $request->get("company_name");
        $position = $request->get("position");

        //验证
         $validations = $this->get("helper.validations");
         if(empty($training_id)){
             return $this->jsonResponse(3,"参数错误");
         }

         if(!$validations->isMobile($phone)){
            return $this->jsonResponse(1,"手机号不正确");
         }
         if(empty($user_name)){
             return $this->jsonResponse(2,"姓名不能为空");
         }

         if(empty($position)){
             return $this->jsonResponse(2,"职位不能为空");
         }

         // 获取公司名称
        $company_array = $conn->fetchAssoc("SELECT company_full_name FROM user WHERE id = '". $this->getUserId() ."' ");

        $company_name = $company_array['company_full_name'];
        if(empty($company_name)){
            return $this->jsonResponse(2,"公司名称错误");
        }

        $apply = $conn->fetchAssoc("SELECT * FROM apply WHERE user_id = '". $this->getUserId() ."' AND training_id = '". $training_id ."'");
        if($apply){
            return $this->jsonResponse(10,"已报名");
        }
        $created_at = date("Y-m-d H:i:s");
        $data = array(
            "training_id" => $training_id,
            "company_name" => $company_name,
            "name" => $user_name,
            "position_name" => $position,
            "phone" => $phone,
            "user_id" => $this->getUserId(),
            "created_at" => $created_at
        );


        $conn->insert("apply",$data);

        return $this->jsonResponse(0,"报名成功");
    }


    /*
     * 得到banner
     */
    public function getBannerAction()
    {
        $conn = $this->get("database_connection");
        $banner = $conn->fetchAll("SELECT * FROM banner WHERE status = 1 AND is_company = 1");
        return $this->jsonResponse(0,"操作成功",$banner);
    }


}
